import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { AppModule } from './app.module';
import { Logger, ValidationPipe } from '@nestjs/common';
import { GlobalResponseInterceptor } from './interceptor/global-response.interceptor';
import { customLogger } from './service/logger.service';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
    }),
  );
  app.enableCors();

  const configService = app.get(ConfigService);

  //动态配置日志
  const enableLog = configService.get('LOG_ENABLE');
  // if (enableLog == 'true') {
  //   app.useLogger(customLogger(configService));
  // }
  app.useLogger(customLogger(configService));

  const options = new DocumentBuilder()
    .setTitle('YM-Admin')
    .setDescription('YM-Admin服务接口文档')
    .setVersion('1.0')
    .addTag('YM-Admin')
    .addBearerAuth()
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('ym/api-docs', app, document);

  app.useGlobalInterceptors(new GlobalResponseInterceptor());

  //捕获未catch的promise，防止挂掉
  process.on('uncaughtException', (reason) => {
    const loggerFormat = `
    timestamp:${new Date().toJSON()} \r\n
    reason:${reason} 
    \r\n
  `;
    Logger.error(loggerFormat);
  });
  process.on('unhandledRejection', (reason) => {
    const loggerFormat = `
    timestamp:${new Date().toJSON()} \r\n
    reason:${reason} 
    \r\n
  `;
    Logger.error(loggerFormat);
  });

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
